package com.legendshop.openportal.sdk.validator;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.legendshop.openportal.sdk.annotation.DateValid;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author jzh
 * @version 1.0.0
 * @title DateValidator
 * @date 2025/5/14 11:18
 * @description：时间字段校验工具类
 */
@Slf4j
public class DateValidator implements ConstraintValidator<DateValid, Object> {

    /**
     * 枚举注解
     */
    private DateValid annotation;

    @Override
    public void initialize(DateValid constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        boolean ignoreEmpty = annotation.ignoreEmpty();
        if (ObjectUtil.isEmpty(value)) {
            if (ignoreEmpty) {
                return Boolean.TRUE;
            }

            log.info("参数为空");
            return Boolean.FALSE;
        }

        String pattern = annotation.pattern();
        if (value instanceof String) {
            String strValue = (String) value;
            try {
                DateUtil.parse(strValue, pattern);
                return Boolean.TRUE;
            } catch (Exception e) {
                return Boolean.FALSE;
            }
        }

        return Boolean.FALSE;
    }
}
